import anydbm
import weakref


class Map(object):
    def __init__(self, filename):
        self._db = anydbm.open(filename, "c")
        if "_key" not in self._db:
            self._db["_key"] = "0"
        MAP = weakref.proxy(self)
        class Object(object):
            __slots__ = ["_key"]
            def __metaclass__(name, bases, dict):
                cls = type(name, bases, dict)
                setattr(MAP, name, cls)
                return cls
            def __init__(s, **kwargs):
                s._key = MAP._genkey()
                for k, v in kwargs.iteritems():
                    setattr(s, k, v)
            def __repr__(self):
                return "<%s instance (%s)>" % (self.__class__.__name__, self._key)
        self.Object = Object
    
    def _genkey(self):
        key = self._db["_key"] = str(int(self._db["_key"]) + 1)
        return key
    
    def close(self):
        self._db.close()
    
    def sync(self):
        self._db.sync()


class Field(object):
    __id = 0
    def __init__(self, type, default = None):
        self.__class__.__id += 1
        self.name = "_%d" % (self.__id,) 
        self.type = type
        self.default = default
    def __get__(self, inst, cls):
        if inst is None:
            return self
        try:
            return getattr(inst, self.name)
        except AttributeError:
            return self.default
    def __set__(self, inst, val):
        setattr(inst, self.name, self.type(val))


m = Map("test.db")
class Person(m.Object):
    first_name = Field(str)
    last_name = Field(str)

p = Person(first_name = "moshe", last_name = "cohen")

print p
print p.first_name
print dir(p)



















